Slide 13

  1. list can store different data types
  2. data frames can store different values with different types
  3. class()
  4. is.character()

Slide 14

Slide 15

    • if() works with scalars; ifelse() works with vectors.
    • when x is TRUE, y will be 3;
    • when FALSE, y will be NULL;
    • when NA the if statement will throw an error.
if("2") 3
if(2) 3

for(i in 1:3){
  print(i)
}

i <- 1
while(i < 4){
  print(i)
  i <- i + 1
}

i <- 1
repeat{
  print(i)
  i <- i + 1 
  if(i > 3) break
  
}

Slide 16

sq_root <- function(x){
  sqrt(x)
}

Exercise slides at the End

  1. Combine all elements of df_list to one data frame. The result should be only a single line of code.
  1. Fix each of the following common data frame subsetting errors:
  1. What does df[is.na(df)] <- 0 do
  1. How would you randomly permute the columns of a data frame?
  1. Write a while and a repeat loop doing the same as
for(i in LETTERS[1:10]){
  print(i)
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# while 
i <- 0
while (i < 10) {
  i = i + 1
  print(LETTERS[i])
  
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# alternative 
i <- 1
while (i < 11) {
  print(LETTERS[i])
  i = i + 1 
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# repeat

i <- 0
repeat{
  i = i + 1
  print(LETTERS[i])
  if (i > 9) {
    break
  }
  
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
# alternative

i <- 1
repeat{
  print(LETTERS[i])
  i = i + 1 
  if (i > 10) {
    break
  }
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
## [1] "E"
## [1] "F"
## [1] "G"
## [1] "H"
## [1] "I"
## [1] "J"
  1. Write a for loop doing the same as
count <- 0
repeat{
  x     <- sample(1:6, 1)
  count <- count + 1 
  if(x == 6) break
}
print(count)
## [1] 12
for (i in 1:100) {
  x     <- sample(1:6, 1)
  count <- i
  if(x == 6) break
}
print(count)
## [1] 6
  1. What is the problem here?
  1. What is the problem here? Can you debug it?
df <- mtcars

lin_mod <- function(df){
lm(y ~ . ,data = df)
}

simple_lin_mod <- function(data, y, x){
df <- data[ ,c(y, x)]
names(df) <- c("y", "x")
lin_mod(df)
}

simple_lin_mod(df, "mpg", "cyl")
## 
## Call:
## lm(formula = y ~ ., data = df)
## 
## Coefficients:
## (Intercept)            x  
##      37.885       -2.876

new

  1. Hallo
  2. World
  3. Germany

Hallo world!

  1. England